package at.fhooe.engine.graphics;

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferStrategy;

public class WindowScreen implements Screen {
	
	private GraphicsDevice m_device = null;
	private Frame m_mainFrame = null;
	private Canvas m_windowCanvas = null;
	private BufferStrategy m_bufferStrategy = null;
	
	@Override
	public void open(int width, int height) {		
		GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        this.m_device = env.getDefaultScreenDevice();
        
		GraphicsConfiguration gc = m_device.getDefaultConfiguration();
        m_mainFrame = new Frame(gc);
        m_mainFrame.setIgnoreRepaint(true);
        
		m_windowCanvas = new Canvas();
		m_windowCanvas.setPreferredSize(new Dimension(width, height));
        m_windowCanvas.setIgnoreRepaint(true);
        
		m_mainFrame.add(m_windowCanvas);
        m_mainFrame.setResizable(false);
		m_mainFrame.pack();
        m_mainFrame.setVisible(true);
        
        m_windowCanvas.requestFocusInWindow();
        m_windowCanvas.createBufferStrategy(2);
        m_bufferStrategy = m_windowCanvas.getBufferStrategy();
	}

	@Override
	public void close() {
		m_device.setFullScreenWindow(null);
		System.exit(0);
	}

	@Override
	public Graphics2D beginUpdate() {
		return (Graphics2D) m_bufferStrategy.getDrawGraphics();
	}

	@Override
	public void endUpdate() {
		m_bufferStrategy.show();
	}

	@Override
	public void addKeyListener(KeyListener keyListener) {
		m_windowCanvas.addKeyListener(keyListener);
	}

	@Override
	public void addMouseListener(MouseListener mouseListener) {
		m_windowCanvas.addMouseListener(mouseListener);
	}

	@Override
	public void addMouseMotionListener(MouseMotionListener mouseMotionListener) {
		m_windowCanvas.addMouseMotionListener(mouseMotionListener);
	}
}
